<template>
	<view style="display: flex;justify-content: center;">
		<view class="container" :style="widthMain">
			<up-form labelPosition="top" labelWidth="auto">
				<view class="form-section">
					<up-form-item label="模型版本" prop="task" borderBottom required>
						<up-radio-group v-if="baseURL!=undefined" v-model="defaultBaseURL"
							@change="groupChangeModelTask">
							<up-radio v-for="(value, key) in baseURL.data" :name="value" :label="key"></up-radio>
						</up-radio-group>
					</up-form-item>
				</view>
			</up-form>
			<up-form :model="formData" :rules="rules" ref="uForm" labelPosition="top" labelWidth="auto">

				<!-- 任务信息卡片 -->
				<!-- <uni-section title="推理信息" type="line"> -->
				<view class="form-section">

					<up-form-item label="推理类型" prop="task" borderBottom required>
						<up-radio-group v-model="formData.task" @change="groupChangeTask">
							<up-radio name="segmentation" label="分割"></up-radio>
							<up-radio name="classification" label="分类"></up-radio>
						</up-radio-group>
					</up-form-item>
					<up-form-item label="身体部位" prop="dataset_name" borderBottom required>

						<view v-show="!isPC" :style="widthMain" 
							style="display: flex; justify-content: flex-start; align-items: flex-start;height: 45rpx;">
							<up-picker-data v-if="formData.task === 'segmentation'" v-model="formData.dataset_name"
								:options="organOptions" title="点击选择分割身体部位" valueKey="value" labelKey="text"
								style="width: 100%;" @click="clearImage" />
							<up-picker-data v-else v-model="formData.dataset_name" :options="organClassOptions"
								title="点击选择分类身体部位" valueKey="value" labelKey="text" 
								style="width: 100%;"
								@click="clearImage" />
							<up-icon name="arrow-down" style="background-color: white; height: 45rpx;"></up-icon>
						</view>
						
						<view v-show="isPC" :style="widthMain"
							style="display: flex; justify-content: flex-start; align-items: flex-start;height: 45rpx;">
							<uni-data-select v-if="formData.task === 'segmentation'" v-model="formData.dataset_name"
								:localdata="organOptions" title="点击选择分割身体部位" valueKey="value" labelKey="text"
								style="width: 100%;" @change="clearImage" />
							<uni-data-select v-else v-model="formData.dataset_name" :localdata="organClassOptions"
								title="点击选择分类身体部位" valueKey="value" labelKey="text" 
								style="width: 100%;"
								@change="clearImage" />
						</view>
					</up-form-item>

				</view>
				<!-- </uni-section> -->

				<!-- 图像信息卡片 -->
				<!-- <uni-section title="图像信息" type="line"> -->
				<view class="form-section">
					<!-- 	<up-form-item label="图像名称[img_name]" prop="img_name" borderBottom required>
						<up-input v-model="formData.img_name" placeholder="输入图像文件名" clearable />
					</up-form-item>

					<up-form-item label="存储路径[img_path_relative]" prop="img_path_relative" borderBottom>
						<up-input v-model="formData.img_path_relative" />
					</up-form-item> -->

					<up-form-item label="图像尺寸(宽×高)" prop="img_dimensions" borderBottom>
						<view class="dimension-group">
							<up-input v-model.number="formData.img_dimensions[0]" type="number" placeholder="宽度"
								class="dimension-input" border="none" disabled />
							<text class="separator">×</text>
							<up-input v-model.number="formData.img_dimensions[1]" type="number" placeholder="高度"
								class="dimension-input" disabled border="none" />

						</view>
					</up-form-item>
					<up-form-item label="文件大小(B)" prop="img_size_bytes" borderBottom>
						<text>{{formData.img_size_bytes}}</text>
					</up-form-item>

					<view v-show="!isPC">
						<up-image
							v-if="formData.img_path_relative.startsWith('/root/autodl-tmp/wsp_uusic/blsamus/data/')"
							:show-loading="true"
							:src="getHref(imageHref,trimChars(formData.img_path_relative,'/root/autodl-tmp/wsp_uusic/blsamus/data/'),'')"
							mode="aspectFill"></up-image>
						<up-image v-else :show-loading="true"
							:src="getHref(imageApi_inHref,trimChars(formData.img_path_relative,'/root/autodl-tmp/wsp_uusic/blsamus/api_in/'),'')"
							mode="aspectFill"></up-image>
					</view>


					<!-- 	<up-form-item label="图像格式[img_format]" prop="img_format" borderBottom required>
						<up-picker-data v-model="formData.img_format" :options="formatOptions" title="选择图像格式"
							valueKey="value" labelKey="label" style="width: 100%;" />
					</up-form-item> -->
				</view>

				<!-- 表单操作按钮 -->
				<view class="action-buttons">
					<up-button type="primary" @click="submitForm" icon="checkmark">提交数据</up-button>
					<up-button @click="randonimage"
						color="linear-gradient(to right, rgb(66, 83, 216), rgb(213, 51, 186))"
						icon="share-square">随机影像</up-button>
					<up-button @click="resetForm" plain icon="reload">重置表单</up-button>
				</view>
				<!-- 表单操作按钮 -->
				<view>
					<!-- 	<view class="u-page__upload-item">
					<up-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" name="1" multiple
						:maxCount="1" :previewFullImage="true"></up-upload>
				</view> -->
					<up-button @click="uploadimage" plain icon="photo">上传影像图片</up-button>
				</view>
			</up-form>
			<up-popup :show="showResult" :round="10" mode="top" @close="closeResult" @open="openResult">
				<scroll-view scroll-y>
					<view style="display: flex;justify-content: center;">
						<view class="page-box" :style="widthMain">
							<view class="order">
								<view class="toptitle">
									<text style="display: flex; justify-content: center;">AI推理结果</text>
								</view>
								<view class="top">
									<view class="left">
										<up-icon name="home" :size="30" color="rgb(94,94,94)"></up-icon>
										<view class="store">{{getOrignLable(result)}}超声影像</view>
										<up-icon name="arrow-right" color="rgb(203,203,203)" :size="26"></up-icon>
									</view>
									<!-- <view class="right">{{ result.mask_name }}</view> -->
								</view>
								<view v-show="!isPC">
									<view style="item">
										<text>原图：{{getOrignLable(result)}}超声影像</text>
									</view>
									<view class="item">
										<up-image
											v-if="formData.img_path_relative.startsWith('/root/autodl-tmp/wsp_uusic/blsamus/data/')"
											:show-loading="true"
											:src="getHref(imageHref,trimChars(formData.img_path_relative,'/root/autodl-tmp/wsp_uusic/blsamus/data/'),'')"
											mode="aspectFill">
											<template v-slot:loading>
												<up-loading-icon color="red"></up-loading-icon>
											</template>
										</up-image>
										<up-image v-else :show-loading="true"
											:src="getHref(imageApi_inHref,trimChars(formData.img_path_relative,'/root/autodl-tmp/wsp_uusic/blsamus/api_in/'),'')"
											mode="aspectFill">
											<template v-slot:loading>
												<up-loading-icon color="red"></up-loading-icon>
											</template>
										</up-image>
									</view>

									<view style="item">
										<text v-if="formData.task === 'segmentation'">AI分割结果</text>
										<text v-else>AI分类结果</text>
									</view>
									<view style="item">
										<up-image v-if="formData.task === 'segmentation'" :show-loading="true"
											:src="getHref(imageOutHref,trimChars(result.mask_path_absolute,'/root/autodl-tmp/wsp_uusic/blsamus/api_out/'),'')"
											mode="aspectFill">
											<template v-slot:loading>
												<up-loading-icon color="red"></up-loading-icon>
											</template>
										</up-image>
										<view v-else>
											<view v-for="(item, index) in result.probability" class="number">
												概率({{getOrignprediction(result, index)}})：{{ item }}
											</view>
											<view class="title up-line-2">
												推测结果: {{ getOrignprediction(result, result.prediction) }}
											</view>
										</view>
									</view>


								</view>
								<view class="item">
									<view class="content">
										<!-- <view class="title up-line-2">{{ result.mask_path_relative }}</view> -->
										<view class="number">推理耗时(秒)：{{ result.inference_time_sec }}</view>
										<view class="number">内存占用(MB)：{{ result.memory_usage_mb }}</view>
										<view class="number">显存占用(MB)：{{ result.gpu_memory_usage_mb }}</view>
										<view class="number">分配显存(MB)：{{ result.gpu_memory_reserved_mb }}</view>
									</view>
									<!-- <view class="right"> 
								<view class="number">time：{{ result.inference_time_sec }}</view>
							</view> -->
								</view>
								<view class="bottom">
									<up-button type="primary" @click="closeResult" style="margin: 0;padding: 0"
										text="确定"></up-button>
								</view>
							</view>
						</view>
						<view v-show="isPC" style="display: flex;justify-content: center;">
							<view>
								<view style="item">
									<text>原图：{{getOrignLable(result)}}超声影像</text>
								</view>
								<view class="item">
									<up-image
										v-if="formData.img_path_relative.startsWith('/root/autodl-tmp/wsp_uusic/blsamus/data/')"
										:show-loading="true"
										:src="getHref(imageHref,trimChars(formData.img_path_relative,'/root/autodl-tmp/wsp_uusic/blsamus/data/'),'')"
										mode="aspectFill" width="800" height="600">
										<template v-slot:loading>
											<up-loading-icon color="red"></up-loading-icon>
										</template>
									</up-image>
									<up-image v-else :show-loading="true"
										:src="getHref(imageApi_inHref,trimChars(formData.img_path_relative,'/root/autodl-tmp/wsp_uusic/blsamus/api_in/'),'')"
										mode="aspectFill">
										<template v-slot:loading>
											<up-loading-icon color="red"></up-loading-icon>
										</template>
									</up-image>
								</view>

							</view>
							<view>
								<view style="item">
									<text v-if="formData.task === 'segmentation'">AI分割结果</text>
									<text v-else>AI分类结果</text>
								</view>
								<view style="item">
									<up-image v-if="formData.task === 'segmentation'" :show-loading="true"
										:src="getHref(imageOutHref,trimChars(result.mask_path_absolute,'/root/autodl-tmp/wsp_uusic/blsamus/api_out/'),'')"
										mode="aspectFill" width="800" height="600">
										<template v-slot:loading>
											<up-loading-icon color="red"></up-loading-icon>
										</template>
									</up-image>
									<view v-else>
										<view v-for="(item, index) in result.probability" class="number">
											概率({{getOrignprediction(result, index)}})：{{ item }}
										</view>
										<view class="title up-line-2">
											推测结果: {{ getOrignprediction(result, result.prediction) }}
										</view>
									</view>
								</view>

							</view>
						</view>
					</view>

				</scroll-view>
			</up-popup>
		</view>
		<view v-show="isPC" class="container"
			style="display: flex; justify-content: center; align-items:left; width: 800px;  background-color: #f8f9fa;">
			<view v-if="formData.img_path_relative==='' ||formData.img_path_relative.length<=0">
				<view style="display: flex; justify-content: center; align-items:center;height: 600px;">
					<text style="color: red;">待上传图片</text>
				</view>
			</view>
			<up-image v-else-if="formData.img_path_relative.startsWith('/root/autodl-tmp/wsp_uusic/blsamus/data/')"
				:show-loading="true"
				:src="getHref(imageHref,trimChars(formData.img_path_relative,'/root/autodl-tmp/wsp_uusic/blsamus/data/'),'')"
				mode="aspectFill" width="800" height="600" bg-color="#f8f9fa"></up-image>
			<up-image v-else :show-loading="true"
				:src="getHref(imageApi_inHref,trimChars(formData.img_path_relative,'/root/autodl-tmp/wsp_uusic/blsamus/api_in/'),'')"
				mode="aspectFill" width="800" height="600" bg-color="#f8f9fa"></up-image>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		inject,
		reactive,
		onActivated,
		onMounted
	} from 'vue'

	// 创建响应式数据  
	const uForm = ref(null)
	const showResult = ref(false);
	const result = ref({
		"img_name": '', //"1.png",
		"img_path_relative": '', //"data/segmentation/KidneyUS/imgs/1.png",
		"img_size_bytes": 0,
		"img_dimensions": [
			0,
			0
		],
		"img_format": "png",
		"task": "segmentation",
		"dataset_name": "KidneyUS",
		"organ": "Kidney",
		"data_partition_group": "public_all",
		"mask_name": '', //"1_mask.png",
		"mask_path_relative": '', //"api_out/segment/1_mask.png",
		"seg_target_info": {},
		"class_label_index": 0,
		"class_label_name": "",
		"mask_path_absolute": '', // "/root/autodl-tmp/wsp_uusic/blsamus/api_out/segment/1_mask.png"
		"probability": [
			0,
			0
		],
		"prediction": 0,
	})
	// 注入变量

	const isPC = ref(false); //uni.$config;
	const config = ref(null); //uni.$config;
	const envType = inject('envType');
	const baseURL = ref(null); //config[envType].API_BASE;
	const defaultBaseURL = ref('');
	//defaultBaseURL.value = GetBaseURL(baseURL.value);

	const href = ref(''); // baseURL + 'segment/';
	const getImageRandohref = ref(''); // baseURL + 'random_sample/';

	const imageHref = ref(''); // baseURL + 'staticdata/';
	const imageApi_inHref = ref(''); // baseURL + 'staticapi_in/';
	const imageOutHref = ref(''); // baseURL + 'staticapi_out/';

	function GetBaseURL(v) {
		let key = v || '标准版';
		return baseURL.value.data[key];
	}

	function UpdateHref(v) {

		// console.log('UpdateHref', v)
		href.value = v + 'segment/';
		console.log('UpdateHref', v, defaultBaseURL.value, href.value)

		getImageRandohref.value = v + 'random_sample/';
		imageHref.value = v + 'staticdata/';
		imageApi_inHref.value = v + 'staticapi_in/';
		imageOutHref.value = v + 'staticapi_out/';

	}
	// 表单数据模型
	const formData = reactive({
		img_name: '', //"1.png",
		img_path_relative: '', //"data/segmentation/KidneyUS/imgs/1.png",
		img_size_bytes: 0,
		img_dimensions: [0, 0],
		img_format: "png",
		task: "segmentation",
		dataset_name: "KidneyUS",
		organ: "Kidney",
		data_partition_group: "public_all",
		mask_name: "",
		mask_path_relative: "",
		seg_target_info: {},
		class_label_index: 0,
		class_label_name: ""
	})

	onMounted(() => {
		console.log("onMounted", envType, "href", href.value)
		try {

			isPC.value = checkPC() || false;
			if (isPC) {
				widthMain.value = 'width: 700rpx;'
			}
			//init config
			config.value = uni.$config;

			if (config.value === undefined || config.value === null) {
				let getConfig = loadConfig();
				console.log("重新加载配置", getConfig)
			} else {
				initload();
			}

		} catch (error) {
			//TODO handle the exception
			console.log(error)
		}
	})
	onActivated(() => {
		console.log("onActivated")
	})

	const widthMain = ref('width: 100%;');

	function initload() {
		console.log("配置信息：", config.value)
		baseURL.value = config.value[envType].API_BASE;
		let defaultKey = baseURL.value.value;
		defaultBaseURL.value = GetBaseURL(defaultKey);

		console.log('默认模型类型', defaultKey)
		UpdateHref(defaultBaseURL.value);
	}

	function checkPC() {
		const systemInfo = uni.getSystemInfoSync();
		console.log('checkPC', systemInfo)
		if (systemInfo.platform === 'windows' || systemInfo.platform === 'mac') {
			// window.location.href = 'https://pc-example.com'; // PC 专属地址 
			console.log('PC端')
			return true;
		} else {
			return checkPCH5();
		}
		return false;

	}

	function loadConfig() {
		// console.warn('当前组件仅支持 uni_modules 目录结构 ，请升级 HBuilderX 到 3.1.0 版本以上！')
		console.log('重新加载配置')
		var tmpdate = new Date();
		console.log(tmpdate.getTime())
		var tmpurl = '/static/config.json?v=' + tmpdate.getTime()
		uni.request({
			url: tmpurl,
			success: (res) => {
				// 挂载到全局
				uni.$config = res.data;
				//, uni.$config
				console.log('重新配置加载成功:');

				config.value = uni.$config;
				initload();

				return res.data;
			}
		});
	}

	function checkPCH5() {
		const userAgent = navigator.userAgent.toLowerCase();

		if (userAgent.includes('windows') ||
			userAgent.includes('macintosh') ||
			userAgent.includes('linux x86_64')) {
			console.log('当前为电脑端（PC）H5');
			return true;
		} else {
			console.log('当前非电脑端H5');
			return false;
		}
	}
	// 选项数据
	const formatOptions = ref([{
			value: 'png',
			text: 'PNG'
		},
		{
			value: 'jpg',
			text: 'JPG'
		},
		{
			value: 'dicom',
			text: 'DICOM'
		},
		{
			value: 'nii',
			text: 'NIfTI'
		}
	])

	//segmentation（分割）
	const organOptions = ref([{
			value: 'BUS-BRA',
			text: '乳腺'
		},
		{
			value: 'CAMUS',
			text: '心脏'
		},
		{
			value: 'Fetal_HC',
			text: '胎儿头部'
		},
		{
			value: 'KidneyUS',
			text: '肾脏'
		},
		{
			value: 'private_Kidney',
			text: '甲状腺'
		}
	])

	// classification（分类）
	const organClassOptions = ref([{
			value: 'private_Appendix',
			text: '阑尾',
			prediction: {
				0: 'normal',
				1: 'abnormal'
			}
		},
		{
			value: 'BUS-BRA',
			text: '乳腺',
			prediction: {
				0: 'benign',
				1: 'maligant'
			}
		},
		{
			value: 'Fatty-Liver',
			text: '脂肪肝',
			prediction: {
				0: 'normal',
				1: 'abnormal'
			}
		},
		{
			value: 'private_Breast_luminal',
			text: '乳腺管腔',
			prediction: {
				0: 'HER2',
				1: "Luminal A",
				2: "Luminal B",
				3: 'Triple Negative'
			}
		}
	])


	function getOrignLable(value) {

		let result = value.dataset_name;

		let arr = [];

		if (value.task === 'segmentation') {
			arr = organOptions.value
		} else {
			arr = organClassOptions.value
		}

		arr.forEach(function(element) {
			// console.log(element)
			// console.log(result, element.value, result === element.value)
			if (result === element.value) {

				result = element.text||element.label
				return;
			}
		}, this);
		return result;
	}

	function getOrignprediction(value, index) {

		console.log(getOrignprediction)

		let result = index + '';
		let filterValue = value.dataset_name;

		let arr = organClassOptions.value;

		arr.forEach(function(element) {
			// console.log(element)
			// console.log(filterValue, element.value, filterValue === element.value)
			if (filterValue === element.value) {

				if (element.prediction !== undefined) {
					result = element.prediction[index]
					return;
				} else {
					result = index + ''
					return;
				}
			}
		}, this);
		return result;
	}

	const partitionOptions = ref([{
			value: 'public_all',
			text: '公开全集[public_all]'
		},
		{
			value: 'train',
			text: '训练集[train]'
		},
		{
			value: 'val',
			text: '验证集[val]'
		},
		{
			value: 'test',
			text: '测试集[test]'
		},
		{
			value: 'private',
			text: '私有数据'
		}
	])

	// 表单验证规则
	const rules = reactive({
		'img_name': [{
			required: true,
			message: '图像名称不能为空',
			trigger: 'blur'
		}],
		// 'img_dimensions': [{
		// 	validator: (rule, value, callback) => {
		// 		if (!value[0] || !value[1]) {
		// 			callback(new Error('请填写完整尺寸'))
		// 		} else if (value[0] <= 0 || value[1] <= 0) {
		// 			callback(new Error('尺寸必须大于0'))
		// 		} else {
		// 			callback()
		// 		}
		// 	},
		// 	trigger: 'blur'
		// }],
		'img_format': [{
			required: true,
			pattern: /^(png|jpg|jpeg|dicom|nii)$/i,
			message: '仅支持PNG/JPG/DICOM/NIfTI格式',
			trigger: 'change'
		}],
		'task': [{
			required: true,
			message: '请选择任务类型',
			trigger: 'change'
		}],
		'dataset_name': [{
			required: true,
			message: '器官数据集名称不能为空',
			trigger: 'blur'
		}],
		'organ': [{
			required: true,
			message: '请选择器官类型',
			trigger: 'change'
		}]
	})


	// 选择掩码文件
	const selectMaskFile = () => {
		uni.chooseFile({
			count: 1,
			success: (res) => {
				if (res.tempFiles.length) {
					const file = res.tempFiles[0]
					formData.mask_name = file.name
					formData.mask_path_relative = `data/masks/${file.name}`
				}
			}
		})
	}

	const groupChangeTask = (n) => {
		console.log('groupChangeTask', n);
		if (n === 'segmentation') {
			formData.dataset_name = 'KidneyUS'
		} else {
			formData.dataset_name = 'private_Appendix'
		}
		clearImage();
	}
	const groupChangeModelTask = (n) => {

		UpdateHref(n)
		// clearImage();
	}

	const clearImage = () => {

		console.log('clearImage')
		formData.img_name = ''
		formData.img_dimensions = []
		formData.img_path_relative = ''
		formData.img_size_bytes = ''
	}
	// 提交表单
	const submitForm = async () => {
		try {
			await uForm.value.validate()

			if (formData.img_dimensions[0] <= 0) {
				uni.showToast({
					title: '请点随机影响，获取一张图片',
					icon: 'error',
					duration: 2000
				})
				return
			}

			uni.showLoading({
				title: '提交中...',
				mask: true
			})

			console.log("data", href.value, formData);

			uni.request({
				url: href.value,
				method: 'POST',
				data: formData
			}).then(res => {
				console.log('request success', res);
				if (res.statusCode != 200) {
					uni.showToast({
						title: '返回数据异常',
						icon: 'error',
						duration: 2000
					})
					return
				}
				uni.showToast({
					title: '返回数据成功',
					icon: 'success',
					duration: 2000
				})
				result.value = res.data || {}
				showResult.value = true

			}).catch(err => {
				console.log('request fail', err);
				uni.showModal({
					content: "请求出错，请稍后再试，谢谢！",
					showCancel: false
				});

			}).finally(() => {
				uni.hideLoading()
			});

			// 实际项目替换为API请求
			// setTimeout(() => {
			// 	uni.hideLoading()
			// 	uni.showToast({
			// 		title: '提交数据成功',
			// 		icon: 'success',
			// 		duration: 2000
			// 	})
			// 	console.log('提交数据：', JSON.stringify(formData))
			// }, 1500)

		} catch (errors) {
			console.log('表单验证失败:', errors)
			uni.showToast({
				title: '请完善表单信息',
				icon: 'error',
				duration: 2000
			})
		}
	}
	// 获取随机图片
	const randonimage = async () => {
		try {
			await uForm.value.validate()

			uni.showLoading({
				title: '获取中...',
				mask: true
			})

			console.log("data", getImageRandohref.value, formData);

			uni.request({
				url: getImageRandohref.value,
				method: 'Get',
				data: {
					task: formData.task,
					dataset_name: formData.dataset_name
				}
			}).then(res => {
				console.log('request success', res);
				if (res.statusCode != 200) {
					uni.showToast({
						title: '返回数据异常',
						icon: 'error',
						duration: 2000
					})
					return
				}
				uni.showToast({
					title: '返回数据成功',
					icon: 'success',
					duration: 2000
				})
				//更新获取的图片信息
				const getdata = res.data;

				formData.img_name = getdata.img_name
				formData.img_dimensions = getdata.img_dimensions
				formData.img_path_relative = getdata.img_path_relative
				formData.img_size_bytes = getdata.img_size_bytes


			}).catch(err => {
				console.log('request fail', err);
				uni.showModal({
					content: "请求出错，请稍后再试，谢谢！",
					showCancel: false
				});

			}).finally(() => {
				uni.hideLoading()
			});

			// 实际项目替换为API请求
			// setTimeout(() => {
			// 	uni.hideLoading()
			// 	uni.showToast({
			// 		title: '提交数据成功',
			// 		icon: 'success',
			// 		duration: 2000
			// 	})
			// 	console.log('提交数据：', JSON.stringify(formData))
			// }, 1500)

		} catch (errors) {
			console.log('表单验证失败:', errors)
			uni.showToast({
				title: '请完善表单信息后再试',
				icon: 'error',
				duration: 2000
			})
		}
	}

	// 重置表单
	const resetForm = () => {
		uForm.value.resetFields()
		formData.seg_target_info = {}
		clearImage()
	}

	// 定义方法  
	function openResult() {
		// 打开逻辑，比如设置 show 为 true  
		showResult.value = true;
		// console.log('open');  
	}

	function closeResult() {
		// 关闭逻辑，设置 show 为 false  
		showResult.value = false;
		// console.log('close');  
	}
	// str: /KidneyUS/imgs
	function getHref(baseHref, str, imagename) {
		const href = baseHref + str + imagename
		console.log(href)
		return href;
	}

	function trimChars(str, chars) {
		return str.replace(new RegExp(`^${chars}|${chars}$`, 'g'), '');
	}

	//上传图片
	const fileList = ref([])

	function uploadimage(v) {
		console.log('uploadimage')

		const uploadurl = trimChars(defaultBaseURL.value, '/') + '/upload'
		console.log('uploadimage', "uploadurl", uploadurl)

		uni.chooseImage({
			success: (chooseImageRes) => {
				const tempFilePaths = chooseImageRes.tempFilePaths;
				console.log('tempFilePaths', tempFilePaths)

				uni.showLoading({
					title: '上传中...',
					mask: true
				})

				const uploadTask = uni.uploadFile({
					url: uploadurl,
					filePath: tempFilePaths[0],
					name: 'file',
					formData: {
						'user': 'test'
					},
					success: (uploadFileRes) => {
						uni.hideLoading()
						console.log(uploadFileRes);
						if (uploadFileRes.statusCode != 200) {
							uni.showToast({
								title: '上传文件失败',
								icon: 'error',
								duration: 2000
							})
							return;
						}
						uni.showToast({
							title: '上传文件成功',
							icon: 'success',
							duration: 2000
						})
						//更新获取的图片信息
						const getdata = JSON.parse(uploadFileRes.data);

						console.log(getdata)

						formData.img_name = getdata.img_name
						formData.img_dimensions = getdata.img_dimensions
						formData.img_path_relative = getdata.img_path_relative
						formData.img_size_bytes = getdata.img_size_bytes

					},
					fail: (errors) => {
						uni.hideLoading()
						console.log('上传文件失败:', errors)
						uni.showToast({
							title: '上传文件失败',
							icon: 'error',
							duration: 2000
						})
					}
				});

				uploadTask.onProgressUpdate((res) => {
					console.log('上传进度' + res.progress);
					console.log('已经上传的数据长度' + res.totalBytesSent);
					console.log('预期需要上传的数据总长度' + res.totalBytesExpectedToSend);

					let msg = '上传进度' + res.progress
					uni.showToast({
						title: msg,
						icon: 'success',
						duration: 1000
					})
					// 测试条件，取消上传任务。
					// if (res.progress > 50) {
					// 	uploadTask.abort();
					// }
				});
			},
			fail: (errors) => {
				uni.hideLoading()
				console.log('上传文件失败:', errors)
				uni.showToast({
					title: '上传文件失败',
					icon: 'error',
					duration: 2000
				})
			}
		});

	}

	// 删除图片
	function deletePic(event) {
		fileList.value.splice(event.index, 1)
	}

	function beforeRead() {
		console.log('beforeRead')
	}
	// 新增图片
	const afterRead = async (event) => {
		// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
		let lists = [].concat(event.file)
		let fileListValue = fileList.value
		let fileListLen = fileListValue.length
		lists.map((item) => {
			fileListValue.push({
				...item,
				status: 'uploading',
				message: '上传中'
			})
		})
		try {

			for (let i = 0; i < lists.length; i++) {
				const result = await uploadFilePromise(lists[i].url)
				let item = fileList[fileListLen]
				fileListValue.splice(fileListLen, 1, Object.assign(item, {
					status: 'success',
					message: '',
					url: result
				}))
				fileListLen++
			}

		} catch (errors) {
			console.log('上传文件失败:', errors)
			uni.showToast({
				title: '上传文件失败',
				icon: 'error',
				duration: 2000
			})
		}
	}

	function uploadFilePromise(url) {
		const uploadurl = trimChars(defaultBaseURL.value, '/') + '/upload'
		console.log('uploadFilePromise', url, "uploadurl", uploadurl)
		return new Promise((resolve, reject) => {
			let a = uni.uploadFile({
				url: uploadurl, // 仅为示例，非真实的接口地址
				filePath: url,
				name: 'file',
				formData: {
					user: 'test'
				},
				success: (res) => {
					setTimeout(() => {
						resolve(res.data.data)
					}, 1000)
				}
			});
		})
	}
</script>

<style lang="scss" scoped>
	.container {
		padding: 20rpx;
		background-color: #f8f9fa;
		height: 93vh;
	}

	.form-section {
		margin: 5rpx;
		padding: 2rpx 0;
	}

	.dimension-group,
	.label-group {
		display: flex;
		align-items: center;
		gap: 15rpx;
	}

	.dimension-input,
	.label-input {
		flex: 1;
	}

	.separator {
		color: #909399;
		font-size: 28rpx;
	}

	.kv-item {
		margin-bottom: 20rpx;
		display: flex;
		align-items: center;

		.key-label {
			min-width: 120rpx;
			padding: 0 15rpx;
			color: #606266;
			font-size: 28rpx;
		}
	}

	.add-target-btn {
		margin-top: 20rpx;
	}

	.action-buttons {
		display: flex;
		gap: 30rpx;
		padding: 40rpx 0;

		:deep(.u-btn) {
			flex: 1;
		}
	}

	:deep(.uni-section__content) {
		padding: 0 20rpx;
	}

	//order list
	.order {
		width: 710rpx;
		background-color: #ffffff;
		// margin: 20rpx auto;
		border-radius: 20rpx;
		box-sizing: border-box;
		padding: 20rpx;
		font-size: 28rpx;

		.toptitle {
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 38rpx;
			font-weight: bolder;
		}

		.top {
			display: flex;
			justify-content: space-between;

			.left {
				display: flex;
				align-items: center;

				.store {
					margin: 0 10rpx;
					font-size: 32rpx;
					font-weight: bold;
				}
			}

			.right {
				color: $u-warning-dark;
			}
		}

		.item {
			display: flex;
			margin: 20rpx 0 0;

			.left {
				margin-right: 20rpx;

				image {
					width: 200rpx;
					height: 200rpx;
					border-radius: 10rpx;
				}
			}

			.content {
				.title {
					font-size: 28rpx;
					line-height: 50rpx;
				}

				.type {
					margin: 10rpx 0;
					font-size: 24rpx;
					color: $u-tips-color;
				}

				.delivery-time {
					color: #e5d001;
					font-size: 24rpx;
				}
			}

			.right {
				margin-left: 10rpx;
				padding-top: 20rpx;
				text-align: right;

				.decimal {
					font-size: 24rpx;
					margin-top: 4rpx;
				}

				.number {
					color: $u-tips-color;
					font-size: 24rpx;
				}
			}
		}

		.total {
			margin-top: 20rpx;
			text-align: right;
			font-size: 24rpx;

			.total-price {
				font-size: 32rpx;
			}
		}

		.bottom {
			display: flex;
			margin-top: 40rpx;
			padding: 0 10rpx;
			justify-content: space-between;
			align-items: center;

			.btn {
				line-height: 52rpx;
				width: 160rpx;
				border-radius: 26rpx;
				border: 2rpx solid $u-border-color;
				font-size: 26rpx;
				text-align: center;
				color: $u-info-dark;
			}

			.evaluate {
				color: $u-warning-dark;
				border-color: $u-warning-dark;
			}
		}
	}

	.centre {
		text-align: center;
		margin: 200rpx auto;
		font-size: 32rpx;

		image {
			width: 164rpx;
			height: 164rpx;
			border-radius: 50%;
			margin-bottom: 20rpx;
		}

		.tips {
			font-size: 24rpx;
			color: #999999;
			margin-top: 20rpx;
		}

		.btn {
			margin: 80rpx auto;
			width: 200rpx;
			border-radius: 32rpx;
			line-height: 64rpx;
			color: #ffffff;
			font-size: 26rpx;
			background: linear-gradient(270deg, rgba(249, 116, 90, 1) 0%, rgba(255, 158, 1, 1) 100%);
		}
	}

	.wrap {
		display: flex;
		flex-direction: column;
		height: calc(100vh - var(--window-top));
		width: 100%;
	}

	.swiper-box {
		flex: 1;
	}

	.swiper-item {
		height: 100%;
	}
</style>